package com.lizard.schedule.ui.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.wearable.activity.ConfirmationActivity;
import android.support.wearable.view.CardScrollView;
import android.support.wearable.view.CircledImageView;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import com.lizard.schedule.R;
import com.lizard.schedule.consts.Path;
import com.lizard.schedule.model.WearSchedule;
import com.lizard.schedule.ui.activity.MainActivity;
import com.lizard.schedule.ui.fragment.base.BaseGoogleApiClientFragment;

/**
 * Created by wangyiqian on 16/6/11.
 */

public class OptionsFragment extends BaseGoogleApiClientFragment {

    private final int CIRCLE_ANIM_DURATION = 2000;

    private CircledImageView finish, delete;

    private ObjectAnimator finishAnimator, deleteAnimator;

    private WearSchedule wearSchedule;

    private Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        wearSchedule = getArguments().getParcelable("wearSchedule");
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.options, container, false);

        CardScrollView cardScrollView = (CardScrollView) view.findViewById(R.id.card_scroll_view);
        cardScrollView.setCardGravity(Gravity.BOTTOM);

        finish = (CircledImageView) view.findViewById(R.id.finish);
        finish.setProgress(0.0f);
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startFinish();
            }
        });
        delete = (CircledImageView) view.findViewById(R.id.delete);
        delete.setProgress(0.0f);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startDelete();
            }
        });

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cancelAllCircleAnim();
    }

    synchronized private void startFinish(){
        if(deleteAnimator != null){
            return;
        }

        if(finishAnimator == null){
            finishAnimator = ObjectAnimator.ofFloat(finish, "progress", 0f, 1f);
            finishAnimator.setDuration(CIRCLE_ANIM_DURATION);
            finishAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                    if(finishAnimator == null){
                        return;
                    }

                    finishAnimator = null;

                    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(Path.CMD_FINISH);
                    putDataMapRequest.getDataMap().putString("timestamp", System.currentTimeMillis() + "");
                    putDataMapRequest.getDataMap().putInt("localId", wearSchedule.getLocalId());
                    PendingResult pendingResult = Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest());
                    pendingResult.setResultCallback(new ResultCallback() {
                        @Override
                        public void onResult(Result result) {
                            if(result.getStatus().isSuccess()) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent(getActivity(), ConfirmationActivity.class);
                                        intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
                                        getActivity().startActivity(intent);
                                        getActivity().finish();
                                    }
                                });
                            }
                        }
                    });

//                    Wearable.NodeApi.getConnectedNodes(googleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
//                        @Override
//                        public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
//                            for(Node node: getConnectedNodesResult.getNodes()){
//
//                                Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), Path.CMD_FINISH, new String(wearSchedule.getLocalId()+"").getBytes())
//                                        .setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
//                                            @Override
//                                            public void onResult(final MessageApi.SendMessageResult sendMessageResult) {
//
//                                                if (sendMessageResult.getStatus().isSuccess()) {
//                                                    handler.post(new Runnable() {
//                                                        @Override
//                                                        public void run() {
//                                                            Intent intent = new Intent(getActivity(), ConfirmationActivity.class);
//                                                            intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
//                                                            getActivity().startActivity(intent);
//                                                            getActivity().finish();
//                                                        }
//                                                    });
//                                                }
//                                            }
//                                        });
//
//                                break;
//                            }
//                        }
//                    });



                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    finishAnimator = null;
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            finishAnimator.start();
        } else{
            finishAnimator.cancel();
            finishAnimator = null;
            finish.setProgress(0f);
        }
    }

    synchronized private void startDelete(){
        if(finishAnimator != null){
            return;
        }

        if(deleteAnimator == null){
            deleteAnimator = ObjectAnimator.ofFloat(delete, "progress", 0f, 1f);
            deleteAnimator.setDuration(CIRCLE_ANIM_DURATION);
            deleteAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {

                    if(deleteAnimator == null){
                        return;
                    }

                    deleteAnimator = null;

                    PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(Path.CMD_DELETE);
                    putDataMapRequest.getDataMap().putString("timestamp", System.currentTimeMillis() + "");
                    putDataMapRequest.getDataMap().putInt("localId", wearSchedule.getLocalId());
                    PendingResult pendingResult = Wearable.DataApi.putDataItem(googleApiClient, putDataMapRequest.asPutDataRequest());
                    pendingResult.setResultCallback(new ResultCallback() {
                        @Override
                        public void onResult(final Result result) {
                            if(result.getStatus().isSuccess()) {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Intent intent = new Intent(getActivity(), ConfirmationActivity.class);
                                        intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
                                        getActivity().startActivity(intent);
                                        getActivity().finish();
                                    }
                                });
                            }
                        }
                    });
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    deleteAnimator = null;
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            deleteAnimator.start();
        } else{
            deleteAnimator.cancel();
            deleteAnimator = null;
            delete.setProgress(0f);
        }
    }



    synchronized private void cancelAllCircleAnim(){
        if(deleteAnimator != null){
            deleteAnimator.cancel();
            deleteAnimator = null;
            delete.setProgress(0f);
        }
        if(finishAnimator != null){
            finishAnimator.cancel();
            finishAnimator = null;
            finish.setProgress(0f);
        }
    }

}
